const Joi = require('joi');
const jwt = require('jsonwebtoken');
module.exports = {
  async login(ctx) {
    const { request, config } = ctx;
    const { body } = request;
    const schema = Joi.object({
      username: Joi.string().required(),
      password: Joi.string().required()
    });
    ctx.validate(schema);
    const { username, password } = body;
    if (username === 'admin' && password === 'admin') {
      const token = jwt.sign({
        username: username,
        password: password
      }, config.jwt.secret, { expiresIn: config.jwt.expired });
      return {
        message: '登录成功',
        token
      };
    } else {
      ctx.throwError('登录失败', 501);
    }
  },
  async detail(ctx) {
    const { params} = ctx;
    const { id } = params;
    if (id > 10) {
      ctx.throwError('用户不存在');
    }
    return {
      username: 'user' + id,
      phone: '152365658954'
    };
  },
  async register(ctx) {
    // const { request } = ctx;
    // const { body } = request;
    const schema = Joi.object({
      username: Joi.string().required(),
      password: Joi.string().required(),
      phone: Joi.string().required()
    });
    ctx.validate(schema);
    // const { username, password } = body;
    return '注册成功';
  }
};